package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.Department;
import org.dromara.system.domain.Equipment;
import org.dromara.system.domain.vo.EquipmentVo;
import org.dromara.system.mapper.DepartmentMapper;
import org.dromara.system.mapper.EquipmentMapper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.DeviceBo;
import org.dromara.system.domain.vo.DeviceVo;
import org.dromara.system.domain.Device;
import org.dromara.system.mapper.DeviceMapper;
import org.dromara.system.service.IDeviceService;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 生产装置Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DeviceServiceImpl implements IDeviceService {

    private final DeviceMapper baseMapper;

    private final EquipmentMapper equipmentMapper;

    private final DepartmentMapper departmentMapper;

    /**
     * 查询生产装置
     *
     * @param id 主键
     * @return 生产装置
     */
    @Override
    public DeviceVo queryById(Long id){
        DeviceVo deviceVo = baseMapper.selectVoById(id);
        if (deviceVo == null) {
            throw new ServiceException("该装置不存在");
        }
        // 查询设备
        LambdaQueryWrapper<Equipment> lqw = Wrappers.lambdaQuery();
        lqw.eq(Equipment::getSszz, deviceVo.getId());
        Map<Long, List<EquipmentVo>> equipmentMap = equipmentMapper.selectVoList(lqw).stream().collect(Collectors.groupingBy(EquipmentVo::getSszz));
        deviceVo.setEquipmentList(equipmentMap.getOrDefault(deviceVo.getId(), Collections.emptyList()));
        // 查询部门
        LambdaQueryWrapper<Department> departmentLqw = Wrappers.lambdaQuery();
        departmentLqw.eq(Department::getId, deviceVo.getCreateDept());
        Department department = departmentMapper.selectOne(departmentLqw);
        deviceVo.setCreateDeptName(department != null ? department.getBmmc() : "");
        return deviceVo;
    }

    /**
     * 分页查询生产装置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 生产装置分页列表
     */
    @Override
    public TableDataInfo<DeviceVo> queryPageList(DeviceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Device> lqw = buildQueryWrapper(bo);
        Page<DeviceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtils.isEmpty(result.getRecords())) {
            return TableDataInfo.build(Collections.emptyList());
        }
        Map<Long, String> deptMap = departmentMapper.selectList().stream().collect(Collectors.toMap(Department::getId, Department::getBmmc));
        Map<Long, List<EquipmentVo>> equipmentMap = equipmentMapper.selectVoList().stream().collect(Collectors.groupingBy(EquipmentVo::getSszz));
        result.getRecords().forEach(deviceVo -> {
            deviceVo.setCreateDeptName(deptMap.getOrDefault(deviceVo.getCreateDept(), ""));
            List<EquipmentVo> equipmentList = equipmentMap.get(deviceVo.getId());
            int equipmentCount = equipmentList == null ? 0 : equipmentList.size();
            deviceVo.setEquipmentCount(equipmentCount);
            deviceVo.setEquipmentList(equipmentMap.getOrDefault(deviceVo.getId(), Collections.emptyList()));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的生产装置列表
     *
     * @param bo 查询条件
     * @return 生产装置列表
     */
    @Override
    public List<DeviceVo> queryList(DeviceBo bo) {
        LambdaQueryWrapper<Device> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Device> buildQueryWrapper(DeviceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Device> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(Device::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getSczzmc()), Device::getSczzmc, bo.getSczzmc());
        lqw.eq(StringUtils.isNotBlank(bo.getSczzbh()), Device::getSczzbh, bo.getSczzbh());
        lqw.eq(bo.getTysj() != null, Device::getTysj, bo.getTysj());
        lqw.eq(StringUtils.isNotBlank(bo.getFzr()), Device::getFzr, bo.getFzr());
        lqw.eq(StringUtils.isNotBlank(bo.getLxfs()), Device::getLxfs, bo.getLxfs());
        lqw.eq(StringUtils.isNotBlank(bo.getZzyt()), Device::getZzyt, bo.getZzyt());
        lqw.eq(bo.getZzzt() != null, Device::getZzzt, bo.getZzzt());
        lqw.eq(Device::getDelFlag, 0);
        return lqw;
    }

    /**
     * 新增生产装置
     *
     * @param bo 生产装置
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(DeviceBo bo) {
        Device add = MapstructUtils.convert(bo, Device.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改生产装置
     *
     * @param bo 生产装置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(DeviceBo bo) {
        Device update = MapstructUtils.convert(bo, Device.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Device entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除生产装置信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
